<template>
  <div class="container">
    <uv-form labelPosition="top" :model="model" :rules="rules" ref="form" labelWidth="300">
      <view v-for="(item, index) in list" :key="index">
        <uv-form-item :label="dict_format(item)" v-if="item.label=='enterprise'" :prop="item.label" borderBottom>
          <view class="positionRelative width100">
            <uv-input :placeholder="`请输入${dict_format(item)}`" v-model="model[item.label]" inputAlign="left" border="none" @input="handleInput"></uv-input>
            <view class="enterpriseWrap" v-if="showEnterprise">
              <view class="box" @click="enterpriseClick(el)" v-for="(el, idx2) in enterpriseList" :key="idx2">
                <view class="fz14 bold">{{el.qymc}}</view>
                <view class="fz12 desc">{{el.dz}}</view>
              </view>
            </view>
          </view>
        </uv-form-item>
        <!-- 下拉选择 -->
        <uv-form-item :label="dict_format(item)" v-else-if="['workYears'].includes(item.label)" :prop="item.label" borderBottom>
          <view class="width100" @click="itemClick(item)">
            <uv-input placeholderStyle="textAlign:left;color:#C0C4CC" inputAlign="left" v-model="model[item.label]" border="none" :placeholder="`请输入${dict_format(item)}`" readonly></uv-input>
          </view>
        </uv-form-item>
        <!-- 输入框 -->
        <uv-form-item :label="dict_format(item)" v-else :prop="item.label" borderBottom>
          <uv-input placeholderStyle="textAlign:left;color:#C0C4CC" inputAlign="left" v-model="model[item.label]" border="none" :placeholder="`请输入${dict_format(item)}`" :disabled="isDisabled(item.label)"></uv-input>
        </uv-form-item>
      </view>
    </uv-form>

    <view class="actionBtn">
      <uv-button text="保 存" shape="circle" @click="onSubmit" color="#4699A6" :loading="loading"></uv-button>
    </view>

    <uvPicker :placeholderStyle="{textAlign:'left',color:'#C0C4CC'}" :placeholder="`请输入${dict_format({'fieldName':fieldName})}`" :columns="[columns]" ref="pickerRef" v-model="model[fieldName]" v-if="fieldName"></uvPicker>
  </div>
</template>

<script setup lang="ts">
import uvPicker from "@/components/uv/uvPicker.vue";
const { proxy } = getCurrentInstance();
const instance = getCurrentInstance();
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();

const validateMobile = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入联系方式"));
  } else if (!proxy.$utils.isPoneAvailable(value)) {
    callback(new Error("请输入正确的联系方式"));
  } else {
    callback();
  }
};

const validateIdCard = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入身份证号"));
  } else if (proxy.$utils.isIdCard(value) != 0) {
    callback(new Error("请输入正确的身份证号"));
  } else {
    callback();
  }
};
let loading = ref(false);
let fieldName = ref("");
let model = ref({
  name: "",
  identityCard: "",
  mobile: "",
  email: "",
  education: "",
  graduationMajor: "",
  workYears: "",
  enterprise: "",
  enterpriseJurisdiction: "",
  enterpriseTax: "",
});
let columns = ref([]);
let list = ref([]);
let dicts = ref([]);
let enterpriseList = ref([]); //企业列表
let showEnterprise = ref(false); //是否显示企业列表
let rules = ref({
  mobile: [{ required: true, validator: validateMobile, trigger: "blur" }],
  identityCard: [
    { required: true, validator: validateIdCard, trigger: "blur" },
  ],
  education: [{ required: true, message: "请输入学历", trigger: "blur" }],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  graduationMajor: [
    { required: true, message: "请输入毕业专业", trigger: "blur" },
  ],
  workYears: [
    { required: true, message: "请输入累计工作年限", trigger: "blur" },
  ],
  enterprise: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  conditions: [{ required: true, message: "请设置报名条件", trigger: "blur" }],
  enterpriseTax: [
    { required: true, message: "请设置所在企业税号", trigger: "blur" },
  ],
  enterpriseJurisdiction: [
    { required: true, message: "请设置所在企业区属", trigger: "blur" },
  ],
});

onShow(() => {
  getDict();
  let aa = { ...counter.ycMpParams.userInfo.baseInfo };
  model.value = proxy.$utils.formatFunction(aa, { ...model.value });
  list.value = proxy.$utils.objTurnArr(model.value);
});

async function getDict() {
  let { data } = await proxy.$apis.getDict({
    type: "details",
    data: {
      code: "user_info",
    },
  });
  dicts.value = data;
}

function dict_format(params) {
  if (!dicts.value.length) return;
  let index = proxy.$utils.findIndexByField(
    dicts.value,
    "dict_code",
    params.label
  );
  if (index != -1) return dicts.value[index].dict_label;
}

async function handleInput(e) {
  enterpriseList.value = await proxy.$apis.autoMatchCompany({
    key: e,
  });
  if (enterpriseList.value.length) {
    if (enterpriseList.value.length == 1) {
      enterpriseClick(enterpriseList.value[0]);
    } else {
      showEnterprise.value = true;
    }
  }
}

function enterpriseClick(e) {
  model.value.enterprise = e.qymc;
  if (model.value.hasOwnProperty("enterpriseTax"))
    model.value.enterpriseTax = e.nsrsbh;
  //所属区属
  if (model.value.hasOwnProperty("enterpriseJurisdiction")) {
    console.log("地址", e);
    let resp = extractAddressInfo(e.dzdh);
    model.value.enterpriseJurisdiction =
      resp.province + resp.city + resp.district;
  }
  showEnterprise.value = false;

  function extractAddressInfo(address) {
    const regex = /(.*省|.*自治区)?(.*市)?(.*区|.*县)?/;
    const matches = address.match(regex);
    if (address.includes("市") && address.includes("区")) {
      let province = matches[1] ? matches[1].trim() : "";
      let city = matches[2] ? matches[2].trim() : "";
      let district = matches[3] ? matches[3].trim() : "";

      return { province, city, district };
    } else {
      // 如果没有找到省市，返回第一个区之前的字符串
      const firstDistrictIndex = address.indexOf("区");
      if (firstDistrictIndex !== -1) {
        let aa = address.substring(0, firstDistrictIndex);
        return { province: "", city: "", district: aa };
      }
    }
  }
}

function isDisabled(e) {
  if (e == "employed_Status") {
    if (model.value.employed_Status.includes("未")) {
      let arr = ["enterprise", "enterpriseTax", "enterpriseJurisdiction"];
      return arr.includes(e);
    }
  } else if (
    counter.ycMpParams.userInfo.baseInfo &&
    counter.ycMpParams.userInfo.baseInfo.hasOwnProperty(e) &&
    counter.ycMpParams.userInfo.baseInfo[e]
  ) {
    return true;
  } else {
    return false;
  }
}

function itemClick(item) {
  let str = `应届毕业年,不满1年,满1年,满2年,满3年,满4年,满5年,满6年,满7年,满8年,满9年,满10年及以上`;
  columns.value = str.split(",");
  fieldName.value = item.label;
  setTimeout(() => {
    instance.refs.pickerRef && instance.refs.pickerRef.open();
  }, 300);
}

async function onSubmit() {
  try {
    loading.value = true;
    await proxy.$apis.student({
      data: model.value,
      type: "perfect",
    });
    proxy.$utils.showToast("修改成功");
    counter.getUserInfo();
    proxy.$utils.back();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}
</script>



<style lang="scss" scoped>
.container {
  padding: 15px 15px 100px 15px;
  .enterpriseWrap {
    position: absolute;
    left: 0;
    z-index: 99999;
    background-color: white;
    padding: 10px;
    box-shadow: 2px 5px 5px 2px #cfcfcf;
    border-radius: 10px;
    max-height: 300px;
    overflow-y: auto;
    .box {
      margin-bottom: 10px;
      .desc {
        color: #999999;
      }
    }
  }
  .actionBtn {
    position: fixed;
    background-color: white;
    padding: 15px 15px 25px 15px;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
  }
}
</style>
